package com.aiwei.tdjk.utils;

import com.aiwei.tdjk.entity.User;
import com.aiwei.tdjk.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.realm.Principal;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpSession;

/**
 * 用户工具类
 *
 * @author HenryYan
 */
public class UserUtil {

    public static final String USER = "user";

    public static final User user = new User();

    /**
     * 设置用户到session
     *
     * @param session
     * @param user
     */
    public static void saveUserToSession(HttpSession session, User user) {
        session.setAttribute(USER, user);
    }

    /**
     * 从Session获取当前用户信息
     *
     * @return
     */
    public static User getUserFromSession() {
        UserService userService = SpringUtils.getBean(UserService.class);
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal)currentUser.getPrincipal();
        if (principal!=null){
            User user = userService.get(principal.getId());
            return user;
        }
        return null;
    }

}
